package com.bullsora.kindlerss.model;

import com.bullsora.kindlerss.model.constraint.Cron;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.bullsora.kindlerss.model.AppUser.getAppUserDependentQuery;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
@EntityListeners(AppUser.AppUserOwnedEntityListener.class)
public class Subscription implements AppUser.AppUserOwnedEntity {

  @NotBlank
  private String prefix;

  @Temporal(TemporalType.TIMESTAMP)
  @DateTimeFormat(style = "M-")
  private Date lastChecked;

  @NotBlank
  @Cron
  private String sendCronExpression;

  private Boolean enabled;

  @OneToMany()
  private Set<Feed> feeds;

  @ManyToOne
  private AppUser appUser;

  @Transient
  private List<Feed> nonEmptyFeeds;

  public static long countSubscriptions() {
    return getAppUserDependentQuery("SELECT COUNT(o) FROM Subscription o", "o", Long.class).getSingleResult();
  }

  public static List<Subscription> findAllSubscriptions() {
    return getAppUserDependentQuery("SELECT o FROM Subscription o", "o", Subscription.class).getResultList();
  }

  public static Subscription findSubscription(Long id) {
    if (id == null) return null;
    return getAppUserDependentQuery("SELECT o FROM Subscription o where o.id = :id", "o", Subscription.class)
        .setParameter("id", id)
        .getSingleResult();
  }

  public static List<Subscription> findSubscriptionEntries(int firstResult, int maxResults) {
    return getAppUserDependentQuery("SELECT o FROM Subscription o", "o", Subscription.class)
        .setFirstResult(firstResult)
        .setMaxResults(maxResults)
        .getResultList();
  }


/*
  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Subscription that = (Subscription) o;

    if (getId() != null ? !id.equals(that.getId()) : that.getId() != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    return getId() != null ? getId().hashCode() : 0;
  }
*/
}
